﻿using System;
using System.Collections.Generic;

namespace smp.ButterflyCakes.Models.ViewModels.Schedule
{
    public class ScheduleCalendar
    {
        //The constructor for this needs to formulate the entire model from just the date and the data in the list.
        public ScheduleCalendar(DateModel model, List<ScheduleListItem> items)
        {
            Weeks = new List<List<ScheduleCalendarItem>>();
            MonthText = model.DisplayMonth;
            YearText = model.DisplayYear;

            var firstOfMonth = model.StartOfMonth;
            DateTime startDate;
            switch(firstOfMonth.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    startDate = firstOfMonth;
                    break;
                case DayOfWeek.Tuesday:
                    startDate = firstOfMonth.AddDays(-1);
                    break;
                case DayOfWeek.Wednesday:
                    startDate = firstOfMonth.AddDays(-2);
                    break;
                case DayOfWeek.Thursday:
                    startDate = firstOfMonth.AddDays(-3);
                    break;
                case DayOfWeek.Friday:
                    startDate = firstOfMonth.AddDays(-4);
                    break;
                case DayOfWeek.Saturday:
                    startDate = firstOfMonth.AddDays(-5);
                    break;
                case DayOfWeek.Sunday:
                    startDate = firstOfMonth.AddDays(-6);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var lastDayOfMonth = model.EndOfMonth;

            var weekIndex = 0;
            for (int i = 0; i < 42; i++)
            {
                var calendarDate = startDate.AddDays(i);
                if(Weeks.Count <= weekIndex)
                {
                    Weeks.Add(new List<ScheduleCalendarItem>());
                }
                Weeks[weekIndex].Add(new ScheduleCalendarItem(calendarDate,
                                                              calendarDate >= firstOfMonth && calendarDate <= lastDayOfMonth,
                                                              items.FindAll(x => x.Date == calendarDate)));

                if(Weeks[weekIndex].Count > 6)
                {
                    if(calendarDate >= lastDayOfMonth)
                        break;
                    weekIndex++;
                }
            }
        }

        public List<List<ScheduleCalendarItem>> Weeks { get; set; }

        public string MonthText { get; private set; }
        public string YearText { get; private set; }
    }
}
